<template>
  <!--<div>-->
  <!--<el-amap vid="amapDemo" :amap-manager="aMapManager" :zoom="zoom"-->
  <!--class="amap-demo"></el-amap>-->
  <!--&lt;!&ndash;搜索&ndash;&gt;-->
  <!--<el-input :value="name" type="text">-->
  <!--</el-input>-->
  <!--<div id="panel"></div>-->
  <!--&lt;!&ndash;公交&ndash;&gt;-->
  <!--<div id="panel1"></div>-->
  <!--&lt;!&ndash;二维码&ndash;&gt;-->
  <!--&lt;!&ndash;<div class="button-group" id='button_group' style='top:15px;bottom:inherit;position: absolute;left: 100px;'>&ndash;&gt;-->
  <!--&lt;!&ndash;<img src="http://a.amap.com/lbs/static/img/js-poisearch.png" style='width:120px;height:120px'>&ndash;&gt;-->
  <!--&lt;!&ndash;</div>&ndash;&gt;-->
  <!--&lt;!&ndash;浏览器定位&ndash;&gt;-->
  <!--<div id="tip1"></div>-->
  <!--&lt;!&ndash;天气预报&ndash;&gt;-->
  <!--<div id="tip" style="line-height: 24px"></div>-->
  <!--</div>-->
  <div>
    <div id="outer-box">
      <el-amap vid="amapDemo" :amap-manager="aMapManager" :zoom="zoom"
               class="amap-demo">
      </el-amap>
      <!--搜索-->
      <div id="panel" class="scrollbar1">
        <div id="searchBar">
          <input id="searchInput" placeholder="输入关键字搜素POI"/>
        </div>
        <div id="searchResults"></div>
      </div>
      <!--步行-->
      <div id="panel1"></div>
      <!--公交-->
      <div id="panel2"></div>
      <!--驾车-->
      <div id="panel3"></div>
      <!--浏览器定位-->
      <div id="tip1"></div>
      <!--提示错误信息-->
      <div id="tip2"></div>
      <!--天气预报-->
      <div id="tip" style="line-height: 24px"></div>
      <div class="input">
        <el-input id="keyword" onfocus='this.value=""' name="keyword"
                  placeholder="起点"></el-input>
        <span class="span"><i class="fa fa-retweet" aria-hidden="true"></i></span>

        <el-input id="keyword1" onfocus='this.value=""' name="keyword"
                  placeholder="终点"></el-input>
        <el-button @click="walk" type="primary" size="mini">步行</el-button>
        <el-button @click="transit" type="primary" size="mini">公交</el-button>
        <el-button @click="drive" type="primary" size="mini">驾车</el-button>
      </div>
    </div>
  </div>

</template>

<script>
  let _this;
  import {lazyAMapApiLoaderInstance} from 'vue-amap';

  export default {
    name: "map1",
    data() {
      return {
        obj: {},
        zoom: 16,
        name: "风景",
        // center: [],//114.98346,30.078384
        aMapManager: this.map,
        map: null,
        origin: null,//起点
        destination: null,//终点
        origin1: null,//起点
        destination1: null,//终点
        city: "",//城市名
        flag: 1,//标记 步行 公交 驾车
        flag1: 2,//标记 步行 公交 驾车
        flag2: 3,//标记 步行 公交 驾车
      }
    },
    created() {
      _this = this;
    },
    mounted() {
      lazyAMapApiLoaderInstance.load().then(() => {
        let center = [], toponymy; //经度  温度   经纬度数组    地名
        toponymy = localStorage.getItem("toponymy");
        center = JSON.parse(localStorage.getItem("coordinate"));
        //自定义定位标记
        let customMarker = new AMap.Marker({
          offset: new AMap.Pixel(-14, -34),//相对于基点的位置
          icon: new AMap.Icon({  //复杂图标
            size: new AMap.Size(27, 36),//图标大小
            image: "http://webapi.amap.com/images/custom_a_j.png", //大图地址
            imageOffset: new AMap.Pixel(-28, 0)//相对于大图的取图位置
          })
        });
        //路况图层
        let defaultLayer = new AMap.TileLayer({textIndex: 15});
        let traffic = new AMap.TileLayer.Traffic();
        //创建地图实例
        _this.map = new AMap.Map('amapDemo', {
          zoom: 17,
          expandZoomRange: true,
          keyboardEnable: false,
          resizeEnable: true,
          zooms: [3, 20],
          layers: [
            defaultLayer,//默认图层
            traffic,//实时交通图层
            new AMap.Buildings()
          ],
        });
        //信息窗体
        let name = localStorage.getItem("designation");
        let city = localStorage.getItem("city");
        //浏览器定位
        AMap.plugin(['AMap.Geolocation', 'AMap.AdvancedInfoWindow', "AMap.Scale", 'AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
          //比例尺，显示当前地图中心的比例尺
          let scale = new AMap.Scale();
          _this.map.addControl(scale);
          let infowindow = new AMap.AdvancedInfoWindow({
            placeSearch: true,
            asOrigin: true,
            asDestination: true,
            content: '<div class="info-title">高德地图</div><div class="info-content">' +
            '<img src="../../static/images/timg.jpg">' +
            '<p>' + name + '。</p><br/></div>',
            offset: new AMap.Pixel(0, -30)
          });
          infowindow.open(_this.map, center);
          _this.obj = infowindow;
          //定位
          let geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: true,        //显示定位按钮，默认：true
            buttonPosition: 'RB',    //定位按钮停靠位置，默认：'RB'，右下角
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          });
          _this.map.addControl(geolocation);
          geolocation.getCurrentPosition();
          AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
          AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
          //输入提示
          let autoOptions = {
            city: city, //城市，默认全国
            input: "keyword"//使用联想输入的input的id
          };
          let autoOptions1 = {
            city: city, //城市，默认全国
            input: "keyword1"//使用联想输入的input的id
          };
          let autocomplete = new AMap.Autocomplete(autoOptions);
          let autocomplete1 = new AMap.Autocomplete(autoOptions1);
          // autocomplete.search(keyword, function (status, result) {
          //   console.log(status, result)
          // });
          let placeSearch = new AMap.PlaceSearch({
            city: city,
            map: _this.map
          });
          AMap.event.addListener(autocomplete, "select", function (e) {
            placeSearch.setCity(e.poi.adcode);
            placeSearch.search(e.poi.name);
            _this.origin = e.poi.name;//选中的值
            _this.origin1 = e.poi.district;//选中值的地址
          });
          AMap.event.addListener(autocomplete1, "select", function (e) {
            placeSearch.setCity(e.poi.adcode);
            placeSearch.search(e.poi.name);
            _this.destination = e.poi.name;//选中的值
            _this.destination1 = e.poi.district;//选中值的地址
          });
        });

        //解析定位结果
        function onComplete(data) {
          let str = ['定位成功'];
          str.push('经度：' + data.position.getLng());
          str.push('纬度：' + data.position.getLat());
          localStorage.setItem("lng", data.position.getLng());
          localStorage.setItem("lat", data.position.getLat());
          localStorage.setItem("toponymy", data.addressComponent.district);
          localStorage.setItem("designation", data.formattedAddress);
          localStorage.setItem("city", data.addressComponent.city);
          if (data.accuracy) {
            str.push('精度：' + data.accuracy + ' 米');
          }//如为IP精确定位结果则没有精度信息
          str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
          document.getElementById('tip1').innerHTML = str.join('<br>');
        }

        //解析定位错误信息
        function onError(data) {
          document.getElementById('tip1').innerHTML = '定位失败';
        }

        //POI选点
        AMapUI.loadUI(['misc/PoiPicker', 'control/BasicControl', 'overlay/SimpleMarker'], function (PoiPicker, BasicControl, SimpleMarker) {
          //窗体信息
          const marker = new SimpleMarker({
            iconLabel: '龚',
            iconStyle: 'beige',
            map: _this.map,
            position: _this.map.getCenter()
          });
          marker.setMap(_this.map);
          marker.on('click', function (e) {
            _this.obj.open(_this.map, e.target.getPosition());
          });
          //添加一个缩放控件
          _this.map.addControl(new BasicControl.Zoom({
            position: 'lb'
          }));
          //图层切换控件
          _this.map.addControl(new BasicControl.LayerSwitcher({
            position: 'rt'
          }));
          let poiPicker = new PoiPicker({
            input: 'searchInput',
            city: toponymy,
            placeSearchOptions: {
              map: _this.map,
              pageSize: 10,
              citylimit: true,
              children: 1,
              renderStyle: "newpc"
            },
            searchResultsContainer: 'searchResults'
          });
          poiPicker.on('poiPicked', function (poiResult) {
            poiPicker.hideSearchResults();
            let source = poiResult.source,
              poi = poiResult.item;
            if (source !== 'search') {
              //suggest来源的，同样调用搜索
              poiPicker.searchByKeyword(poi.name);
            } else {
              //console.log(poi);
            }
          });
          poiPicker.onCityReady(function () {
            poiPicker.searchByKeyword('美食');
          });
        });
        //查询
        AMap.service(['AMap.Weather'], function () {
          //天气预报
          let weather = new AMap.Weather();
          //查询实时天气信息, 查询的城市到行政级别的城市，如朝阳区、杭州市
          weather.getLive(toponymy, function (err, data) {
            if (!err) {
              let str = [];
              str.push('<div style="color: #3366FF;">实时天气' + '</div>');
              str.push('<div>城市/区：' + data.city + '</div>');
              str.push('<div>天气：' + data.weather + '</div>');
              str.push('<div>温度：' + data.temperature + '℃</div>');
              str.push('<div>风向：' + data.windDirection + '</div>');
              str.push('<div>风力：' + data.windPower + ' 级</div>');
              str.push('<div>空气湿度：' + data.humidity + '</div>');
              str.push('<div>发布时间：' + data.reportTime + '</div>');
              let marker = new AMap.Marker({map: _this.map, position: center});
              let infoWin = new AMap.InfoWindow({
                content: str.join(''),
                offset: new AMap.Pixel(0, -20)
              });
              infoWin.open(_this.map, center);
              marker.on('mouseover', function () {
                infoWin.open(_this.map, center);
              });
            }
          });
          //未来4天天气预报
          toponymy = localStorage.getItem("toponymy");
          weather.getForecast(toponymy, function (err, data) {
            if (err) {
              return;
            }
            let str = [];
            for (let i = 0, dayWeather; i < data.forecasts.length; i++) {
              dayWeather = data.forecasts[i];
              str.push(dayWeather.date + ' <div class="weather">' + dayWeather.dayWeather + '</div> ' + dayWeather.nightTemp + '~' + dayWeather.dayTemp + '℃');
            }
            document.getElementById('tip').innerHTML = str.join('<br>');
          });
        });
      })
    },
    methods: {
      //步行
      walk() {
        if (this.origin && this.destination) {
          AMap.service(["AMap.Walking"], function () {
            //步行导航
            let walking = new AMap.Walking({
              map: _this.map,
              panel: "panel1"
            });
            walking.search([{keyword: _this.origin, city: _this.origin1}, {
              keyword: _this.destination,
              city: _this.destination1
            }], (status, result) => {
              if (status !== "complete" && result.info !== "ok") {
                _this.$message.warning(result.info);
              } else {
                _this.map.clearMap();
              }
            });
          })
        } else {
          this.$message.warning("请正确填写起终点！");
        }
      },
      //公交
      transit() {
        if (this.origin && this.destination) {
          AMap.service(["AMap.Transfer"], function () {
            let transOptions = {
              map: _this.map,
              city: _this.origin1,//公交城市
              cityd: _this.destination1,
              panel: "panel2",
              policy: AMap.TransferPolicy.LEAST_TIME //乘车策略
            };
            //构造公交换乘类
            let trans = new AMap.Transfer(transOptions);
            //根据起、终点坐标查询公交换乘路线
            trans.search([{keyword: _this.origin}, {keyword: _this.destination}], (status, result) => {
              if (status !== "complete" && result.info !== "ok") {
                _this.$message.warning(result.info);
              } else {
                _this.map.clearMap();
              }
            });
          });
        } else {
          this.$message.warning("请正确填写起终点！");
        }
      },
      //驾车
      drive() {
        if (this.origin && this.destination) {
          AMap.service(["AMap.Driving"], function () {
            //构造路线导航类
            let driving = new AMap.Driving({
              map: _this.map,
              panel: "panel3"
            });
            // 根据起终点名称规划驾车导航路线
            driving.search([
              {keyword: _this.origin, city: _this.origin1},
              {keyword: _this.destination, city: _this.destination1}
            ], (status, result) => {
              if (status !== "complete" && result.info !== "ok") {
                _this.$message.warning(result.info);
              } else {
                _this.map.clearMap();
              }
            });
          })
        } else {
          this.$message.warning("请正确填写起终点！");
        }
      },
    }
  }
</script>

<style>
  /*错误信息*/
  .el-message {
    min-width: 260px;
    top: 50px;
  }

  /*地图*/
  .amap-demo {
    width: 100%;
    height: 100%;
    position: absolute;
    overflow: hidden;
    font: 12px Helvetica, 'Hiragino Sans GB', 'Microsoft Yahei', '微软雅黑', Arial;
  }

  .amap-info-contentContainer {
    margin-bottom: 9px;
  }

  .info-title {
    color: white;
    font-size: 14px;
    background-color: rgba(0, 155, 255, 0.8);
    line-height: 26px;
    padding: 0 0 0 6px;
    font-weight: lighter;
    letter-spacing: 1px;
  }

  .info-content {
    padding: 4px;
    display: flex;
    align-items: center;
  }

  .info-content p {
    color: #666666;
    line-height: 30px;
    font-size: 16px;
  }

  .info-content img {
    float: left;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin: 3px;
  }

  /*搜索*/
  #outer-box {
    height: 100%;
    padding-right: 300px;
  }

  .input {
    position: absolute;
    top: 0;
    left: 400px;
    right: 0;
    display: flex;
  }

  .el-input {
    width: 200px;
  }

  .el-input__inner {
    text-align: center;
    height: 30px;
    line-height: 30px;
  }

  .span {
    font-size: 18px;
    height: 30px;
    line-height: 30px;
    display: block;
    margin: 0 5px;
    cursor: pointer;
  }

  .el-button--mini, .el-button--mini.is-round {
    padding: 7px 8px;
    margin-left: 20px;
  }

  #panel {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    height: auto;
    max-height: 80%;
    overflow: auto;
    width: 300px;
    z-index: 999;
    border-left: 1px solid #eaeaea;
    background: #fff;
  }

  #searchBar {
    height: 30px;
    background: #ccc;
  }

  #searchInput {
    width: 100%;
    height: 30px;
    line-height: 30%;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: none;
    border-bottom: 1px solid #ccc;
    padding: 0 5px;
    text-align: center;
    font-weight: bold;
    font-size: 16px;
  }

  #searchResults {
    overflow: auto;
    height: calc(100% - 30px);
  }

  .amap_lib_placeSearch,
  .amap-ui-poi-picker-sugg-container {
    border: none !important;
  }

  .amap_lib_placeSearch .poibox.highlight {
    background-color: #CAE1FF;
  }

  .poi-more {
    display: none !important;
  }

  /*公交*/
  #panel1, #panel2, #panel3 {
    position: fixed;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 10px;
    right: 10px;
    width: 280px;
    border-bottom: solid 1px silver;
  }

  /*二维码*/

  /*.marker {
  width: 22px;
  height: 36px;
  background-image: url(http://webapi.amap.com/theme/v1.3/markers/b/mark_b.png);
  background-size: 22px 36px;
  text-align: center;
  line-height: 24px;
  color: #fff
  }*/

  .amap-logo, .amap-copyright {
    display: none !important;
  }

  .amap-ui-control-position-bl, .amap-ui-control-position-lb {
    bottom: 66px !important;
  }


</style>
